package at.fhj.swd10.eshop.shopping;

import at.fhj.swd10.eshop.domain.Product;
import at.fhj.swd10.eshop.web.application.ShopData;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

/**
 * @author David
 */
@ManagedBean(name = "shoppingCartBean")
@SessionScoped
public class ShoppingCartBean {

    @ManagedProperty(value = "#{shopData}")
    private ShopData shopData;
    private List<Product> shoppingCart = new ArrayList<Product>();

    public String insertProduct() throws Exception {
        int id = extractProductIdOutOfContext();
        Product product = shopData.getProductById(id);
        shoppingCart.add(product);
        return "shoppingCart";
    }

    public String deleteProduct() throws Exception {
        int id = extractProductIdOutOfContext();
        Product product = shopData.getProductById(id);
        shoppingCart.remove(product);
        return "shoppingCart";
    }

    private int extractProductIdOutOfContext() throws Exception {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        return Integer.parseInt(context.getRequestParameterMap().get("index"));
    }

    public int getCount() {
        return shoppingCart.size();
    }

    public float getPrice() {
        float price = 0.0f;
        for (Product product : shoppingCart) {
            price += product.getPrice();
        }
        return Math.round(price * 100f) / 100.00f;
    }

    public String downloadPdf() throws Exception {
        Document document = new Document();
        PdfWriter.getInstance(document, createFileOutputStream());

        document.setHeader(createHeaderFooter("Goalkeeper E-Shop PDF", false));
        document.setFooter(createHeaderFooter("Page: ", true));
        document.open();
        document.add(new Paragraph(" "));
        document.add(new Paragraph(" "));

        PdfPTable table = new PdfPTable(new float[]{3f, 3f, 5f, 3f, 3f});
        table.addCell(createPdfPTopCell("Category"));
        table.addCell(createPdfPTopCell("Label"));
        table.addCell(createPdfPTopCell("Product"));
        table.addCell(createPdfPTopCell("Size"));
        table.addCell(createPdfPTopCell("Price"));

        if (!shoppingCart.isEmpty()) {
            for (Product p : shoppingCart) {
                table.addCell(createPdfPCell(p.getCategory().getName()));
                table.addCell(createPdfPCell(p.getLabel().getName()));
                table.addCell(createPdfPCell(p.getName()));
                table.addCell(createPdfPCell(p.getSize()));
                table.addCell(createPdfPCell(p.getPrice() + ""));
            }
        }

        table.addCell(createPdfPTopCell(""));
        table.addCell(createPdfPTopCell(""));
        table.addCell(createPdfPTopCell(""));
        table.addCell(createPdfPTopCell(""));
        table.addCell(createPdfPTopCell(getPrice() + ""));

        document.add(table);
        document.close();

        shoppingCart.clear();
        return "shoppingOverview";
    }

    private FileOutputStream createFileOutputStream() throws Exception {
        ResourceBundle systemProperties = ResourceBundle.getBundle("properties.system");
        String directory = systemProperties.getString("desktopDirectory");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        File f = new File(directory + "order_" + sdf.format(new Date()) + ".pdf");
        f.setWritable(true);
        return new FileOutputStream(f);
    }

    private HeaderFooter createHeaderFooter(String text, boolean number) {
        HeaderFooter hf = new HeaderFooter(new Phrase(text, new Font(Font.HELVETICA, 12, Font.BOLD)), number);
        hf.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.TOP | Rectangle.BOTTOM);
        hf.setAlignment(Element.ALIGN_CENTER);
        return hf;
    }

    private PdfPCell createPdfPTopCell(String text) {
        PdfPCell cell = new PdfPCell(new Phrase(text, new Font(Font.HELVETICA, 14, Font.BOLD)));
        cell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.TOP | Rectangle.BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        return cell;
    }

    private PdfPCell createPdfPCell(String text) {
        PdfPCell cell = new PdfPCell(new Phrase(text, new Font(Font.HELVETICA, 12, Font.NORMAL)));
        cell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.TOP | Rectangle.BOTTOM);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        return cell;
    }

    public ShopData getShopData() {
        return shopData;
    }

    public void setShopData(ShopData shopData) {
        this.shopData = shopData;
    }

    public List<Product> getShoppingCart() {
        return shoppingCart;
    }

    public void setShoppingCart(List<Product> shoppingCart) {
        this.shoppingCart = shoppingCart;
    }
}
